package com.scalar.chiptrack.finance.creditNote.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.finance.creditNote.forms.CreditNoteSendMailForm;
import com.scalar.chiptrack.finance.creditNote.forms.CreditNoteForm;
import com.scalar.chiptrack.finance.creditNote.dao.CreditNoteDAO;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.commons.*;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.MessageResources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.mail.internet.InternetAddress;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

/**
 * User: Sujan
 * Date: Apr 30, 2007
 * Time: 8:24:19 PM
 */
public class CreditNoteSendMailAction extends ChipTrackAction
{
    public CreditNoteSendMailAction () { }

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response )
    {

        HashMap info = new HashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new HashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        CreditNoteSendMailForm creditNoteSendMailForm = (  CreditNoteSendMailForm ) form;
        String salesOrderId = request.getParameter ( "salesOrderId" );
        String creditNoteId = request.getParameter ( "creditNoteId" );
        SalesOrder salesOrder = null;
        CreditNoteForm creditNoteForm= new CreditNoteForm();
        boolean success = false;
        String action = request.getParameter ( "action" );

        request.setAttribute ( "salesOrderId", salesOrderId );
        request.setAttribute ( "creditNoteId", creditNoteId );

        int externalUserEmailsLength = 0;
        ArrayList contactPersons = null;
        String types[] = null;

        String subject = null;
        String[] toUsers = null;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        try
        {
            if ( creditNoteId != null )
            {

                creditNoteForm.setCreditNoteId(Integer.parseInt(creditNoteId));
                CreditNoteDAO.loadCreditNote (null, creditNoteForm );
                ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                creditNoteForm.setClientInfo( clientInfo );
                salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );
            }
        }
        catch ( ScalarException se )
        {
            System.out.println ( "Exception while loading Credit/Debit Note ..... " );
            se.getRootCause ().printStackTrace ();
        }

        String mimeType = creditNoteSendMailForm.getAttachMIMEType ();

        if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
        {
            mimeType = "PDF";
            creditNoteSendMailForm.setAttachMIMEType ( "PDF" );
        }


        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/creditNotesendAckMail.do?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        if ( ( action != "loadMail" ) && ( action.equalsIgnoreCase ( "send" ) ) )
        {
            try
            {
                String to = StringUtils.concatStrings ( creditNoteSendMailForm.getToUsers (), Mailer.EMAIL_SEPARATOR );
                String cc = StringUtils.concatStrings ( creditNoteSendMailForm.getCcUsers (), Mailer.EMAIL_SEPARATOR );
                String bcc = StringUtils.concatStrings ( creditNoteSendMailForm.getBccUsers (), Mailer.EMAIL_SEPARATOR );

                to = Mailer.getNotifiableEmails ( to, false );
                cc = Mailer.getNotifiableEmails ( cc, false );
                bcc = Mailer.getNotifiableEmails ( bcc, false );

                if ( cc == null )
                {
                    creditNoteSendMailForm.setCcUsers ( null );
                }
                if ( bcc == null )
                {
                    creditNoteSendMailForm.setBccUsers ( null );
                }
                subject = creditNoteSendMailForm.getSubject ();

                if ( subject == null )
                {
                    if( "Credit".equalsIgnoreCase(creditNoteForm.getNoteType()) )
                    {
                        subject = " Credit Note Acknowledgement for "+ creditNoteForm.getCreditNoteNumber();
                    }
                    else
                    {
                        subject = " Debit Note Acknowledgement for "+ creditNoteForm.getCreditNoteNumber();
                    }
                }
                creditNoteSendMailForm.setSubject ( subject );
                String message = creditNoteSendMailForm.getMessage ().replaceAll("\n", "<br>");
                String host = request.getHeader ( "HOST" );
                String creditNoteAckFile = null;
                if ( "PDF".equalsIgnoreCase ( mimeType ) )
                    creditNoteAckFile = getcreditNoteAckPDFFile ( host, creditNoteForm );
                else
                    creditNoteAckFile = getCreditNoteAckHtmlFile ( host, creditNoteForm );

                String[] mailAttachments = null;

                String isConfirm = ( String ) session.getAttribute ( "isConfirm" );
                String sysAdminEmail = ConfigManager.getSysAdminEmail ();
                String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
                if ( isConfirm == null )
                {
                    to = Mailer.getNotifiableEmails ( to, false );
                    cc = Mailer.getNotifiableEmails ( cc, false );
                    bcc = Mailer.getNotifiableEmails ( bcc, false );
                    InternetAddress[] toAddress = null;
                    InternetAddress[] ccAddress = null;
                    InternetAddress[] bccAddress = null;

                    String emailIds = "";
                    if ( to != null )
                    {
                        toAddress = InternetAddress.parse ( to );
                        for ( int i = 0; i < toAddress.length; i++ )
                        {
                            InternetAddress temp = toAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                 emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }
                    if ( cc != null )
                    {
                        ccAddress = InternetAddress.parse ( cc );
                        for ( int i = 0; i < ccAddress.length; i++ )
                        {
                            InternetAddress temp = ccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                    emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                    emailIds = emailIds +", "+ temp.getAddress () ;
                                }

                            }
                        }
                    }
                    if ( bcc != null )
                    {
                        bccAddress = InternetAddress.parse ( bcc );
                        for ( int i = 0; i < bccAddress.length; i++ )
                        {
                            InternetAddress temp = bccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if(emailIds == "" )
                                {
                                    emailIds = emailIds + temp.getAddress () ;
                                }
                                else
                                {
                                    emailIds = emailIds +", "+ temp.getAddress () ;
                                }
                            }
                        }
                    }

                    if ( emailIds.trim ().length () > 0 )
                    {
                        errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                        info.put ( "Emails ", emailIds );

                        session.setAttribute ( "isConfirm", "True" );
                        return mapping.findForward ( "success" );
                    }

                }
                mailAttachments = new String[]{creditNoteAckFile};
                Mailer.send (  creditNoteSendMailForm.getFromUser() , to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
                info.put ( "Email has been sent successfully", null );
                session.removeAttribute ( "ShowAgain" );
                session.removeAttribute ( "isConfirm" );
            }
            catch ( Exception se )
            {
                success = false;
                String errMessage = "Error";
                errors.put ( errMessage, "Could not send Email. Please check the EmailId" );
                se.printStackTrace ();
                return mapping.findForward ( "success" );
            }
            return ( mapping.findForward ( "sendAckMailView" ) );
        }
        else if ( "showContactPersonDetails".equalsIgnoreCase ( action ) )
        {
            try
            {
                String value = ( String ) session.getAttribute ( "ShowAgain" );
                if ( "True".equals ( value ) )
                {
                    contactPersons = ( ArrayList ) session.getAttribute ( "contactPersons" );
                }
                else
                {
                    contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
                    String[]  externalUserEmails = SalesOrderDAO.loadEmailListForSalesOrderNotification();

                    int contactPersonsSize = 0;

                    if( externalUserEmails != null )
                    {
                        externalUserEmailsLength = externalUserEmails.length;
                    }
                    if( contactPersons != null )
                    {
                        contactPersonsSize = contactPersons.size();
                    }
                    ArrayList  userEmailsList = new ArrayList();
                    int userEmailsSize = 0;

                    try
                    {
                        userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_SALES_ORDERS);
                    }
                    catch( ScalarException se )
                    {
                        se.getRootCause().printStackTrace();
                        System.out.println( "Exception while retrieving email list");
                    }
                    if ( userEmailsList != null )
                    {
                        userEmailsSize = userEmailsList.size();
                    }
                    types = new String[ contactPersonsSize + externalUserEmailsLength + userEmailsSize + 2 ];

                    int i = 0;
                    for ( i = 0; i < contactPersonsSize; i++ )
                    {
                        ContactPerson contactPerson = ( ContactPerson ) contactPersons.get ( i );

                        if ( contactPerson.getSalesAckMail() )
                        {
                            contactPerson.setIsChecked ( true );
                        }
                        types[i] = "Contact Person";
                   }
                   int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );
                   String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                   String salesPersonEmail = CustomerDAO.getSalesPersonEmail(null, salesOrder.getSalesPerson(),salesOrder.getCustomerId());

                   if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                   {
                       ContactPerson customer = new ContactPerson();
                       customer.setContactPerson(salesOrder.getCustomerName());
                       customer.setEmail( customerEmail );
                       contactPersons.add(customer);
                       types[i++] = "Customer";
                   }
                   if ( salesPersonEmail != null && !"".equals(salesPersonEmail.trim()) )
                   {
                       ContactPerson salesPerson = new ContactPerson();
                       salesPerson.setContactPerson(salesOrder.getSalesPerson());
                       salesPerson.setEmail( salesPersonEmail );
                       salesPerson.setIsChecked ( true );
                       contactPersons.add(salesPerson);
                       types[i++] = "Sales Person";
                   }
                   ContactPerson externalUser[] = new ContactPerson[externalUserEmailsLength];
                   for (int j = 0; j < externalUserEmailsLength; j++) {
                        externalUser[j] = new ContactPerson();
                        externalUser[j].setEmail( externalUserEmails[j] );
                        externalUser[j].setIsChecked( true );
                        contactPersons.add(externalUser[j]);
                        types[i++] = "Notification";
                   }
                   if ( userEmailsList != null && userEmailsSize > 0 )
                    {
                       for( int j = 0; j < userEmailsSize; j++ )
                       {
                           ContactPerson customer = new ContactPerson();
                           StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                           String userName = st.nextToken ();
                           String userEmail = st.nextToken ();
                           customer.setContactPerson( userName );
                           customer.setEmail( userEmail );
                           customer.setIsChecked( true );
                           contactPersons.add(customer);
                           types[i++] = "User";
                       }
                    }
                   session.setAttribute ("types",types);
                }
            }
            catch ( ScalarException e )
            {
                e.printStackTrace ();
            }
            session.setAttribute ( "ShowAgain", "False" );
            request.setAttribute ( "contactPersons", contactPersons );

            return ( mapping.findForward ( "showContactPersons" ) );
        }
        else if ( "displayMailIds".equalsIgnoreCase ( action ) )
        {
            try
            {
                contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );

                int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( salesOrder.getCustomerId() );

                String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                String salesPersonEmail = CustomerDAO.getSalesPersonEmail(null, salesOrder.getSalesPerson(),salesOrder.getCustomerId());
                String[]  externalUserEmails = SalesOrderDAO.loadEmailListForSalesOrderNotification();
                ArrayList  userEmailsList = new ArrayList();
                int userEmailsSize = 0;

                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_SALES_ORDERS);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                if ( userEmailsList != null )
                {
                    userEmailsSize = userEmailsList.size();
                }
                if( externalUserEmails != null )
                {
                    externalUserEmailsLength = externalUserEmails.length;
                }
                if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                {
                    ContactPerson customer = new ContactPerson();
                    customer.setContactPerson(salesOrder.getCustomerName());
                    customer.setEmail( customerEmail );
                    contactPersons.add(customer);
                }
                if ( salesPersonEmail != null && !"".equals(salesPersonEmail.trim()) )
                {
                    ContactPerson salesPerson = new ContactPerson();
                    salesPerson.setContactPerson(salesOrder.getSalesPerson());
                    salesPerson.setEmail( salesPersonEmail );
                    contactPersons.add(salesPerson);
                }
                ContactPerson externalUser[] = new ContactPerson[externalUserEmailsLength];
                for (int i = 0; i < externalUserEmailsLength; i++) {
                    externalUser[i] = new ContactPerson();
                    externalUser[i].setEmail( externalUserEmails[i] );
                    contactPersons.add(externalUser[i]);
                }
                if ( userEmailsList != null && userEmailsSize > 0 )
                {
                   for( int j = 0; j < userEmailsSize; j++ )
                   {
                       ContactPerson customer = new ContactPerson();
                       StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(j), "/" );
                       String userName = st.nextToken ();
                       String userEmail = st.nextToken ();
                       customer.setContactPerson( userName );
                       customer.setEmail( userEmail );
                       contactPersons.add(customer);
                   }
                }
                for ( int i = 0; i < contactPersons.size (); i++ )
                {
                    ContactPerson contactPerson = ( ContactPerson ) contactPersons.get ( i );
                    if ( request.getParameter ( "selectedValue" + i ) != null )
                    {
                        contactPerson.setIsChecked ( true );
                    }
                }

                session.setAttribute ( "contactPersons", contactPersons );
                session.setAttribute ( "ShowAgain", "True" );
            }
            catch ( Exception se )
            {
                System.out.println ( "Exception while loading sales order acknowledgement emails.. " );
            }
            return ( mapping.findForward ( "success" ) );
        }

        try
        {            
            creditNoteSendMailForm.setFromUser( ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME ) );
            subject = creditNoteSendMailForm.getSubject ();
            ContactPerson cperson = null;
            if ( subject == null )
            {
                if( "Credit".equalsIgnoreCase(creditNoteForm.getNoteType()) )
                {
                    subject = " Credit Note Acknowledgement for "+ creditNoteForm.getCreditNoteNumber();
                }
                else
                {
                    subject = " Debit Note Acknowledgement for "+ creditNoteForm.getCreditNoteNumber();
                }
            }
            creditNoteSendMailForm.setSubject ( subject );

            toUsers = creditNoteSendMailForm.getToUsers();

            if(toUsers == null)
            {
                contactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, salesOrder );
                String salesPersonEmail = CustomerDAO.getSalesPersonEmail(null, salesOrder.getSalesPerson(),salesOrder.getCustomerId());
                String[]  externalUserEmails = SalesOrderDAO.loadEmailListForSalesOrderNotification();
                ArrayList  userEmailsList = new ArrayList();
                int userEmailsSize = 0;
                try
                {
                    userEmailsList = UserDAO.loadEmailsByType(Constants.USER_NOTIFICATION_EMAIL_TYPE_FOR_SALES_ORDERS);
                }
                catch( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    System.out.println( "Exception while retrieving email list");
                }
                int contactPersonsSize = contactPersons.size ();
                if( externalUserEmails != null )
                {
                    externalUserEmailsLength = externalUserEmails.length;
                }
                if( userEmailsList != null )
                {
                   userEmailsSize = userEmailsList.size();
                }
                String [] mailTo =new String[ contactPersonsSize + externalUserEmailsLength + userEmailsSize + 2 ];
                int i = 0;
                int j = 0;
                int k = 0;
                for ( i = 0; i < contactPersonsSize ; i++ )
                {
                   cperson = ( ContactPerson ) contactPersons.get ( i );
                   if(cperson.getSalesAckMail())
                   {
                        mailTo[ i ] = cperson.getEmail();
                   }
                }
                for ( j = 0; j < externalUserEmailsLength; j++) {
                    mailTo[ i + j ] = externalUserEmails[ j ];
                }
                for ( k = 0; k < userEmailsSize; k++) {
                    StringTokenizer st = new StringTokenizer ( ( String )userEmailsList.get(k), "/" );
                    String userName = st.nextToken ();
                    String userEmail = st.nextToken ();
                    mailTo[ i + j + k ] = userEmail;
                }
                if ( salesPersonEmail != null && !"".equals( salesPersonEmail ) )
                {
                    mailTo[ i + j + k + 1 ] = salesPersonEmail;
                }
                creditNoteSendMailForm.setToUsers(mailTo);
            }
        }

        catch ( Exception se )
        {
            System.out.println ( "Exception while loading sales order acknowledgement emails.. "+se );
        }
        session.removeAttribute ( "ShowAgain" );
        session.removeAttribute ( "isConfirm" );
        creditNoteSendMailForm.setCustomerId ( creditNoteForm.getCustomerId () );
        request.setAttribute ( "creditNoteSendMailForm", creditNoteSendMailForm );
        return ( mapping.findForward ( "success" ) );
    }
    public static String getcreditNoteAckPDFFile ( String host, CreditNoteForm creditNoteForm ) throws ScalarException
    {
           String fileXMLPath = null;
           String filePDFPath = null;
           String fileXSLTPath = null;
           int customerId = creditNoteForm.getCustomerId ();
           String saAsXML = formatAsXML ( creditNoteForm  );

           if ( saAsXML == null )
           {
               return fileXMLPath;
           }

           FileWriter fWriter = null;
           File saPDFAttachment = null;
           File saXML = null;
           try
           {
               // CREATE TEMPORARY ATTACHMENT FILE
               String mailingTempDir = ConfigManager.getMailerTempDir ();
               File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
               tempDir.mkdir ();

               String creditNoteNo = creditNoteForm.getCreditNoteNumber() ;
               String xmlFileName, saAttachmentPDFFileName;

               xmlFileName = creditNoteForm.getNoteType() +" Note " + creditNoteNo + ".xml";
               saAttachmentPDFFileName = creditNoteForm.getNoteType() +"_Note_ " + creditNoteNo + ".pdf";

               String xsltFileName = ConfigManager.getCreditNoteAckXml2PdfXslFile ();

               saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
               saXML.deleteOnExit ();

               saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
               saPDFAttachment.deleteOnExit ();

               if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
               {
                   fWriter = new FileWriter ( saXML, false );
                   fWriter.write ( saAsXML );
                   fWriter.close ();
                   fWriter = null;

                   fileXMLPath = saXML.getCanonicalPath ().toLowerCase ();
                   filePDFPath = saPDFAttachment.getCanonicalPath ().toLowerCase ();
                   boolean success = PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );

               }
           }
           catch ( Exception e )
           {
               System.out.println ( "Exception while creating Credit Note Ack PDF file" );
               e.printStackTrace ();
           }
           finally
           {
               if ( fWriter != null )
               {
                   try
                   {
                       fWriter.close ();
                       fWriter = null;
                   }
                   catch ( IOException ignore )
                   {
                   }
               }
           }

           return filePDFPath;
       }
    public static String formatAsXML ( CreditNoteForm creditNoteForm ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        String heading = null;
        heading =  creditNoteForm.getNoteType() +  " Note Acknowledgement";

        buf.append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" );
        buf.append ( "<creditNoteAcknowledgement>" + "\n" );
        buf.append ( "<logo>" + ConfigManager.getChipTracImagesDir () + ConfigManager.getScalarLogo () + "</logo>" + "\n" );

        buf.append("<heading><![CDATA[" +heading+ "]]></heading>"+"\n");

        buf.append ( "<selfAddress>" + "\n" );
        buf.append ( "<name><![CDATA[" + creditNoteForm.getClientInfo().getClientName()  + "]]></name>" + "\n" );
        Address clientAddress = creditNoteForm.getClientInfo().getAddress();

        buf.append ( "<address1><![CDATA[" + clientAddress.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + clientAddress.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + clientAddress.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + clientAddress.getAddress4 () + "]]></address4>" + "\n" );
        StringBuffer cityStateZip = new StringBuffer ( "" );

        if ( !clientAddress.getCity ().equals ( "" ) ) cityStateZip.append ( clientAddress.getCity () + ", " );
        if ( !clientAddress.getState ().equals ( "" ) ) cityStateZip.append ( clientAddress.getState () + " - " );
        if ( !clientAddress.getZipCode ().equals ( "" ) ) cityStateZip.append ( clientAddress.getZipCode () + ", " );
        cityStateZip.append ( clientAddress.getCountry () );

        buf.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );

        StringBuffer phFax = new StringBuffer ();
        if ( !clientAddress.getPhoneNumber ().equals ( "" ) ) phFax.append ( "Tel:" + clientAddress.getPhoneNumber () + ", " );
        if ( !clientAddress.getFaxNumber ().equals ( "" ) ) phFax.append ( "Fax:" + clientAddress.getFaxNumber () );

        buf.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );


        buf.append ( "</selfAddress>" + "\n" );
        Address address = creditNoteForm.getBillingAddress();
        String customerName = creditNoteForm.getCustomerName ();
        if ( creditNoteForm.getCustomerName ().equals ( creditNoteForm.getBillingAddress().getContactPerson () ) )
        {
            customerName = null;
        }

        buf.append ( "<billToAddress>" + "\n" );
        if( creditNoteForm.getBillingAddress().getContactPerson() != null && creditNoteForm.getCustomerName().trim().length() !=0 )
        {
            if( ! creditNoteForm.getBillingAddress().getContactPerson().equals( creditNoteForm.getCustomerName() ) )
            {
                buf.append ( "<name><![CDATA[" + customerName + "]]></name>" + "\n" );
            }
        }
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );
        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );

        buf.append ( "</billToAddress>" + "\n" );

        address = creditNoteForm.getShippingAddress ();

        buf.append ( "<shipToAddress>" + "\n" );
        buf.append ( "<name><![CDATA[" + creditNoteForm.getCustomerName () + "]]></name>" + "\n" );
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if( address.getState ()!=null && !(address.getState ().equals("")) )
        {
            buf.append(address.getState());
        }
        if( address.getZipCode()!=null && !(address.getZipCode().equals("")) )
        {
            if( address.getState()!=null && !(address.getState ().equals("")) )
            {
                buf.append("-");
            }
            buf.append( address.getZipCode() );
        }
        if( address.getCountry ()!=null && !(address.getCountry ().equals("")) )
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );
        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );

        buf.append ( "</shipToAddress>" + "\n" );

        buf.append ( "<information>" + "\n" );
        buf.append ( "<creditNoteNo><![CDATA[" + creditNoteForm.getCreditNoteNumber()  + "]]></creditNoteNo>" + "\n" );
        buf.append ( "<noteType><![CDATA[" + creditNoteForm.getNoteType()  + "]]></noteType>" + "\n" );
        buf.append ( "<customer><![CDATA[" + creditNoteForm.getCustomerName()  + "]]></customer>" + "\n" );
        buf.append ( "<customerPO><![CDATA[" + creditNoteForm.getCustomerPONo()  + "]]></customerPO>" + "\n" );
        buf.append ( "<payTerms><![CDATA[" +creditNoteForm.getPayTerms()  + "]]></payTerms>" + "\n" );
        buf.append ( "<dateIssued><![CDATA[" + creditNoteForm.getIssueDate()  + "]]></dateIssued>" + "\n" );
        buf.append ( "<salesOrderNo><![CDATA[" + creditNoteForm.getSalesOrderNo()  + "]]></salesOrderNo>" + "\n" );
        buf.append ( "<salesRep><![CDATA[" + creditNoteForm.getSalesRep()  + "]]></salesRep>" + "\n" );
        buf.append ( "<endUser><![CDATA[" + creditNoteForm.getEndUserName()  + "]]></endUser>" + "\n" );
        buf.append ( "<endCustomer><![CDATA[" + creditNoteForm.getEndCustomerName()  + "]]></endCustomer>" + "\n" );
        buf.append ( "<packingSlipLabel><![CDATA[" + creditNoteForm.getPackingSlipLabel()  + "]]></packingSlipLabel>" + "\n" );
        buf.append ( "<isConsiderUnits><![CDATA[" + (creditNoteForm.getIsUnits() ? "Yes" : "No")  + "]]></isConsiderUnits>" + "\n" );

        buf.append ( "</information>" + "\n" );
        buf.append ( "<comments><![CDATA[" + creditNoteForm.getComments () + "]]></comments>" + "\n" );
/*
            LineItem lineItem = null;
            ArrayList CancelItemListWithSubtotals = creditNoteForm.getCancelledLineItems();
        if (CancelItemListWithSubtotals.size()>0)
        {
            buf.append ( "<cancelLineItems>" + "\n" );

            String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
            if ( mfgPartNumberLabel == null )
            {
                mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
            }

            String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
            if ( customerPartNumberLabel == null )
            {
                customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
            }

            buf.append ( "<labelMfgPartNumber><![CDATA[" + mfgPartNumberLabel + "]]></labelMfgPartNumber>" );
            buf.append ( "<labelCustPartNumber><![CDATA[" + customerPartNumberLabel + "]]></labelCustPartNumber>" );
            boolean lineItemsPresent = false;
            for ( int i = 0; i < CancelItemListWithSubtotals.size (); i++ )
            {
                HashMap hashMap = ( HashMap ) CancelItemListWithSubtotals.get ( i );
                Iterator iterator = hashMap.keySet ().iterator ();
                if( !hashMap.isEmpty())
                {
                    lineItemsPresent = true;
                }
                while ( iterator.hasNext () )
                {
                    ArrayList list = ( ArrayList ) iterator.next ();
                    SubTotal subTotal = ( SubTotal ) hashMap.get ( list );
                    String subTotalQty = subTotal.getSubTotalQty ();
                    String subTotalAmt = subTotal.getSubTotalAmt ();


                    int size = list.size ();
                    buf.append ( "<group>" + "\n" );

                    for ( int j = 0; j < size; j++ )
                    {
                        lineItem = ( LineItem ) list.get ( j );
                        buf.append ( "<lineItem>" + "\n" );
                        buf.append ( "<crLineItem><![CDATA[" + lineItem.getLineItemNo()  + "]]></crLineItem>" + "\n" );
                        buf.append ( "<poLineItem><![CDATA[" + lineItem.getPoLineItemNo()  + "]]></poLineItem>" + "\n" );
                        buf.append ( "<mfgPartNumber><![CDATA[" + lineItem.getManufacturingPartNo () + "]]></mfgPartNumber>" + "\n" );
                        buf.append ( "<customerPartNumber><![CDATA[" + lineItem.getCustomerPartNo () + "]]></customerPartNumber>" + "\n" );
                        buf.append ( "<description><![CDATA[" + lineItem.getDescription () + "]]></description>" + "\n" );
                        buf.append ( "<shipedQty><![CDATA[" + lineItem.getShippedQtyAsString()  + "]]></shipedQty>" + "\n" );
                        buf.append ( "<shipDate><![CDATA[" + lineItem.getShippedDate()  + "]]></shipDate>" + "\n" );
                        buf.append ( "<unitPrice><![CDATA[" + lineItem.getUnitPriceAsString()  + "]]></unitPrice>" + "\n" );
                        buf.append ( "<amount><![CDATA[" + lineItem.getAmountAsString() + "]]></amount>" + "\n" );
                        buf.append ( "<reason><![CDATA[" +  lineItem.getReason() + "]]></reason>" + "\n" );
                        buf.append ( "<discount><![CDATA[" + lineItem.getAdjustmentQtyAsString()  + "]]></discount>" + "\n" );
                        buf.append ( "<discountAmount><![CDATA[" + lineItem.getDiscountAmountAsString()  + "]]></discountAmount>" + "\n" );
                        buf.append ( "</lineItem>" + "\n" );
                    }
                    buf.append ( "<subTotalQty><![CDATA[" + subTotalQty + "]]></subTotalQty>" + "\n" );
                    buf.append ( "<subTotalAmt><![CDATA[" + subTotalAmt + "]]></subTotalAmt>" + "\n" );
                    buf.append ( "</group>" + "\n" );
                }
            }
            buf.append ( "</cancellineItems>" + "\n" );
        }
        */
        LineItem lineItem = null;
        ArrayList presentListWithSubtotals = creditNoteForm.getLineItems();
        buf.append ( "<lineItems>" + "\n" );
        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }

        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }

        buf.append ( "<labelMfgPartNumber><![CDATA[" + mfgPartNumberLabel + "]]></labelMfgPartNumber>" );
        buf.append ( "<labelCustPartNumber><![CDATA[" + customerPartNumberLabel + "]]></labelCustPartNumber>" );
        boolean lineItemsPresent = false;
        for ( int i = 0; i < presentListWithSubtotals.size (); i++ )
        {
                    lineItemsPresent= true;
                    lineItem = ( LineItem ) presentListWithSubtotals.get ( i );
                    buf.append ( "<lineItem>" + "\n" );
                    buf.append ( "<crLineItem><![CDATA[" + lineItem.getLineItemNo()  + "]]></crLineItem>" + "\n" );
                    buf.append ( "<poLineItem><![CDATA[" + lineItem.getPoLineItemNo()  + "]]></poLineItem>" + "\n" );
                    buf.append ( "<mfgPartNumber><![CDATA[" + lineItem.getManufacturingPartNo () + "]]></mfgPartNumber>" + "\n" );
                    buf.append ( "<customerPartNumber><![CDATA[" + lineItem.getCustomerPartNo () + "]]></customerPartNumber>" + "\n" );
                    buf.append ( "<description><![CDATA[" + lineItem.getDescription () + "]]></description>" + "\n" );
                    buf.append ( "<shipedQty><![CDATA[" + lineItem.getShippedQtyAsString()  + "]]></shipedQty>" + "\n" );
                    buf.append ( "<shipDate><![CDATA[" + lineItem.getShippedDate()  + "]]></shipDate>" + "\n" );
                    buf.append ( "<unitPrice><![CDATA[" + lineItem.getUnitPriceAsString()  + "]]></unitPrice>" + "\n" );
                    buf.append ( "<amount><![CDATA[" + lineItem.getAmountAsString() + "]]></amount>" + "\n" );
                    buf.append ( "<reason><![CDATA[" +  lineItem.getReason() + "]]></reason>" + "\n" );
                    buf.append ( "<adjustmentQty><![CDATA[" + lineItem.getAdjustmentQtyAsString()  + "]]></adjustmentQty>" + "\n" );
                    buf.append ( "<discount><![CDATA[" + lineItem.getDiscountPriceAsString()  + "]]></discount>" + "\n" );
                    buf.append ( "<discountAmount><![CDATA[" + lineItem.getDiscountAmountAsString()  + "]]></discountAmount>" + "\n" );
                    buf.append ( "</lineItem>" + "\n" );
        }
        buf.append ( "</lineItems>" + "\n" );
        buf.append ("<lineItemsNotPresentMessage>");
        if( !lineItemsPresent )
        {
            buf.append("All the line items have been cancelled.");
        }
        buf.append("</lineItemsNotPresentMessage>");
        buf.append ( "<totalAdjustmentAmount><![CDATA[" + creditNoteForm.getTotalAdjustmentAmountAsString() + "]]></totalAdjustmentAmount>" + "\n" );
         if(ConfigManager.getShowTermsLabel() )
        {
            buf.append ( "<notes><termsLabel>" + Constants.TERMS_LABEL + "</termsLabel></notes>" );
        }

        buf.append ( "<termsPage1>" + ConfigManager.getChipTracImagesDir () + "/Terms and Condition of Sale.jpg</termsPage1>" + "\n" );
        buf.append ( "</creditNoteAcknowledgement>" + "\n" );

        return buf.toString ();
    }

    public static String getCreditNoteAckHtmlFile ( String host, CreditNoteForm creditNoteForm  ) throws ScalarException
    {
        String filePath = null;
        String psAsHtml = formatAsHTML ( host, creditNoteForm );

        if ( psAsHtml == null )
        {
            return filePath;
        }
        FileWriter fWriter = null;
        File psAttachment = null;
        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();
            String creditNoteAttachmentFileName = null;
            String creditNoteNo = creditNoteForm.getCreditNoteNumber() ;
            creditNoteAttachmentFileName = creditNoteForm.getNoteType() + "_Note_" + creditNoteNo + ".html";
            psAttachment = new File ( tempDir.getCanonicalPath (), creditNoteAttachmentFileName );
            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );
                fWriter.write ( psAsHtml );
                fWriter.close ();
                fWriter = null;
                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Credit Note Ack html file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }
        return filePath;
    }
    public static String formatAsHTML ( String host, CreditNoteForm creditNoteForm  ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        String heading = null;
        heading = creditNoteForm.getNoteType() + " Note ";
        buf.append ( "<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>" );
        buf.append ( "<LINK href='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet>" );
        buf.append ( "<style type='text/css'>" );
        buf.append ( "a { text-decoration : none}" );
        buf.append ( "</style>" );
        buf.append ( "</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" );
        buf.append ( "<!-- from here your body starts -->" );
        buf.append ( "<Div1><table width='98%' cellspacing='0' cellpadding='0' border=0 align=center>" );
        buf.append ( " <tr>" );
        buf.append ( "<td width='34%' align='left' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/scalar_logo.jpg' height='72' width='180' border=0></td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        Address clientAddress = creditNoteForm.getClientInfo().getAddress();
        buf.append ( "<td width='30%' align='center' class='NArialL'>");
        buf.append ( "<table border=0 cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td align='center' nowrap><h3>" + heading + "Acknowledgement</h3></td></tr>" );
        buf.append ( "<tr><td align='center' class='NArialL'>" ).append( creditNoteForm.getClientInfo().getClientName()).append( "</td></tr>" );
        buf.append ( "<tr><td align='center' class='NArialL'>" ).append ( creditNoteForm.getClientAddrWithOutEmailObjFormatted() ).append ( "</td></tr>" );
        buf.append ( "</table></td>" );

        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( " <td width='34%' align=center><font class='NArialW'>" );
        buf.append ( " </font></td>" );
        buf.append ( " </tr>" );
        buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        String customerName = creditNoteForm.getCustomerName ();
                Address address = creditNoteForm.getBillingAddress();
                String addressValue = address.getAddressAsString();
                if ( creditNoteForm.getCustomerName ().equals ( creditNoteForm.getBillingAddress().getContactPerson () ) )
                {
                    customerName = null;
                }
                buf.append ( " <tr>" );
                buf.append ( " <td colspan=6 height='100%' align='left' valign='top'>" );
                buf.append ( " <table  height='100%' border=0 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
                buf.append ( "  <tr><td width='49%' height='100%'>" );
                buf.append ( "      <table height='100%' border=0 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
                buf.append ( "      <tr height=20><td width='100%'class='NArialL' bgcolor='#DEE1E2'>Billing Address :</td></tr>" );
                buf.append ( "      <tr height=20><td width='100%' valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
                buf.append ( "      <table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
                buf.append ( "          <tr><td width='100%' height='100%' align='left' valign='top'>" );
                buf.append (            creditNoteForm.getBillingAddressAsHTML() + "</td></tr>" );
                buf.append ( "      </table></td>" );
                buf.append ( "      </tr>" );
                buf.append ( "</table>" );
                buf.append ( "</td>" );

                Address address2 = creditNoteForm.getShippingAddress();
                buf.append ( "<td width='2%' height='100%' align='left' valign='top'>" );
                buf.append ( "<img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
                /*buf.append ( "<td width='30%' height='100%' align='left' valign='top'>" );
                buf.append ( "<img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
                buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );*/
                buf.append ( "<td width='49%' height='100%' align='left' valign='top'>" );
                buf.append ( " <table height='100%' border=0 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
                buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Shiping Address :</td></tr>" );
                buf.append ( "<tr height=20><td valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
                buf.append ( "<table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
                buf.append ( "<tr><td width='100%' height='100%' align='left' valign='top'>" );
                buf.append (  creditNoteForm.getShippingAddressAsHTML() + "</td></tr>" );
                buf.append ( "</table></td>" );
                buf.append ( "</tr>" );
                buf.append ( "</table>" );
                buf.append ( "</td>" );
                buf.append ( "</tr>" );

                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

                buf.append ( "<tr>" );
                buf.append ( "<td  width ='49%' class='NArialL' height='100%'>" );
                buf.append ( "<table width='100%' height='100%'class='NArialL' border=0 bordercolor='#000000' cellspacing='1' cellpadding='0'>" );
                buf.append ( "<tr ><td bgcolor='#DEE1E2'>" + creditNoteForm.getNoteType() + " Note # : </td>");
                buf.append ( "<td bgcolor='#DEE1E2'>Sales Order #</td>");
                buf.append ( "<td bgcolor='#DEE1E2'>Date Issued</td>");
                buf.append ( "<td bgcolor='#DEE1E2'>Customer PO #</td>");
                buf.append ( "</tr>");
                buf.append ( "<tr ><td bgcolor='#FFFFEE'>"+creditNoteForm.getCreditNoteNumber()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getSalesOrderNo()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getIssueDate()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getCustomerPONo()+"</td>");
                buf.append ( "</tr>" );
                buf.append ( "</table>" );
                buf.append ( "</td>" );
                buf.append ( "<td width='2%' height='100%' align='left' valign='top'>" );
                buf.append ( "<img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
                /*buf.append ( "<td width='30%' height='100%' align='left' valign='top'>" );
                buf.append ( "<img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
                buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );*/
                buf.append ( "<td width='49%' height='100%' align='left' valign='top'>" );
                buf.append ( "<table width='100%' height='100%'class='NArialL' border=0 bordercolor='#000000' cellspacing='1' cellpadding='0'>" );
                buf.append ( "<tr><td bgcolor='#DEE1E2'>Customer</td>");
                buf.append ( "<td bgcolor='#DEE1E2'>End Customer</td>");
                buf.append ( "<td bgcolor='#DEE1E2'>End User</td>");
                buf.append ( "<td bgcolor='#DEE1E2'>Sales Rep</td>");
                buf.append ( "<td bgcolor='#DEE1E2'>Pay Terms</td>");
                buf.append ( "</tr>");
                buf.append ( "<tr ><td bgcolor='#FFFFEE'>"+creditNoteForm.getCustomerName()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getEndCustomerName()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getEndUserName()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getSalesRep()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+creditNoteForm.getPayTerms()+"</td>");
                buf.append ( "</tr>" );
                buf.append ( "</table>" );
                buf.append ( "</td>" );
                buf.append ( "</tr>" );

                buf.append ( "<tr><td>&nbsp;</td></tr>" );
                buf.append ( "<tr>" );
                buf.append ( "<td  width ='49%' class='NArialL' height='100%'>" );
                buf.append ( "<table width='60%' height='100%'class='NArialL' border=0 bordercolor='#000000' cellspacing='1' cellpadding='0'>" );
                buf.append ( "<tr><td  bgcolor='#DEE1E2'>Packing Slip Label : </td>");
                buf.append ( "<td  bgcolor='#DEE1E2'>Is Consider Units</td>");
                buf.append ( "<td>&nbsp;</td>");
                buf.append ( "<td>&nbsp;</td>");
                buf.append ( "</tr>");
                buf.append ( "<tr><td bgcolor='#FFFFEE'>"+creditNoteForm.getPackingSlipLabel()+"</td>");
                buf.append ( "<td bgcolor='#FFFFEE'>"+ ( creditNoteForm.getIsUnits() ? "Yes" : "No" ) + "</td>");
                buf.append ( "<td>&nbsp;</td>");
                buf.append ( "<td>&nbsp;</td>");
                buf.append ( "</tr>" );
                buf.append ( "</table>" );
                buf.append ( "</td>" );
                buf.append ( "<td width='2%' height='100%' align='left' valign='top'>" );
                buf.append ( "<img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
                buf.append ( "<td width='49%' height='100%' align='left' valign='top'>" );
                /*buf.append ( "<table width='100%' height='100%'class='NArialL' border=0 bordercolor='#000000' cellspacing='0' cellpadding='1'>" );
                buf.append ( "<tr bgcolor='#DEE1E2'><td>&nbsp;</td>");
                buf.append ( "</tr>");
                buf.append ( "<tr bgcolor='#FFFFEE'><td>&nbsp;</td>");
                buf.append ( "<td>&nbsp;</td>");
                buf.append ( "</tr>" );
                buf.append ( "</table>" );*/
                buf.append ( "</td>" );
                buf.append ( "</tr>" );

                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );



                buf.append ( "<tr><td colspan=6 class='NArialL'><U>Comments:</U></td></tR>" );
                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
                buf.append ( "<tr><td colspan=6 class='NArialL' bgcolor='#FFFFEE'>" + ( creditNoteForm.getComments() != null && !creditNoteForm.getComments().equals("") ?  creditNoteForm.getComments() : "" )  + "&nbsp;</td></tR>" );
                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=10></td></tR>" );

                LineItem lineItem = null;
                ArrayList CancelLineItemsListWithSubtotals = creditNoteForm.getCancelledLineItems();
                boolean canceledLineItemsPresent = false;
                if(CancelLineItemsListWithSubtotals.size ()>0)
                {
                    buf.append ( "<tr><td colspan=6 class='NArialL'>Cancelled LineItems</td></tr>");
                    buf.append ( "<tr><td colspan='6'>" );
                    buf.append ( "<table width='100%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
                    buf.append ( "<tr height=20>" );
                    buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Line Item #</td>" );
                    buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>PO Line Item #</td>" );
                    String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
                    if ( mfgPartNumberLabel == null )
                    {
                        mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
                    }

                    buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + mfgPartNumberLabel + "</td>" );

                    String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
                    if ( customerPartNumberLabel == null )
                    {
                        customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
                    }
                    buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + customerPartNumberLabel + "</td>" );
                    buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Description</td>" );
                    buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Shipped Qty</td>" );
                    buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Ship Date</td>" );
                    buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Unit Price</td>" );
                    buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Amount</td>" );
                    buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Reason</td>" );
                    buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Change To<br>Qty</td>" );
                    buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Change To<br> Price</td>" );
                    buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Change To<br> Amount</td>" );
                    buf.append ( "</tr>" );
                    lineItem = null;

                    for ( int i = 0; i < CancelLineItemsListWithSubtotals.size (); i++ )
                    {

                                lineItem = ( LineItem ) CancelLineItemsListWithSubtotals.get ( i );
                                buf.append ( "<tr height=20>" );
                                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getLineItemNo () + "&nbsp;</td>" );
                                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getPoLineItemNo() + "&nbsp;</td>" );
                                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getManufacturingPartNo () + "&nbsp;</td>" );
                                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getCustomerPartNo () + "&nbsp;</td>" );
                                buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' wrap>" + lineItem.getLineItemDescription () + "&nbsp;</td>" );
                                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getShippedQtyAsString()  + "&nbsp;</td>" );
                                buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getShippedDate () + "&nbsp;</td>" );
                                buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getUnitPriceAsString () + "&nbsp;</td>" );
                                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getAmountAsString()  + "&nbsp;</td>" );
                                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" +  lineItem.getReason() + "&nbsp;</td>" );
                                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center nowrap>" + lineItem.getAdjustmentQtyAsString()  + "&nbsp;</td>" );
                                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=right nowrap>" + lineItem.getDiscountPriceAsString()  + "&nbsp;</td>" );
                                buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=right nowrap>" + lineItem.getDiscountAmountAsString()  + "&nbsp;</td>" );
                                buf.append ( "</tr>" );
                    }
                    buf.append ( "</table>" );
                    buf.append ( "</td></tr>" );
                }

                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=10></td></tR>" );
                buf.append ( "<tr><td colspan=6 class='NArialL'>Current Line Items</td></tr>" );
                buf.append ( "<tr><td colspan='6'>" );
                buf.append ( "<table width='100%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
                buf.append ( "<tr height=20>" );
                buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Line Item #</td>" );
                buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>PO Line Item #</td>" );
                String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
                if ( mfgPartNumberLabel == null )
                {
                    mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
                }

                buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + mfgPartNumberLabel + "</td>" );

                String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
                if ( customerPartNumberLabel == null )
                {
                    customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
                }

                buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + customerPartNumberLabel + "</td>" );
                buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Description</td>" );
                buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Shipped Qty</td>" );
                buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Ship Date</td>" );
                buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Unit Price</td>" );
                buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Amount</td>" );
                buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Reason</td>" );
                buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Change To<br>Qty</td>" );
                buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Change To<br> Price</td>" );
                buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Change To<br> Amount</td>" );
                buf.append ( "</tr>" );

                lineItem = null;
                ArrayList presentListWithSubtotals = creditNoteForm.getLineItems();
                boolean lineItemsPresent = false;
                if(presentListWithSubtotals.size ()>0)
                {
                    lineItemsPresent = true;
                }
                for ( int i = 0; i < presentListWithSubtotals.size (); i++ )
                {
                            lineItem = (LineItem) presentListWithSubtotals.get ( i );
                            buf.append ( "<tr height=20>" );
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getLineItemNo () + "&nbsp;</td>" );
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getPoLineItemNo() + "&nbsp;</td>" );
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getManufacturingPartNo () + "&nbsp;</td>" );
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getCustomerPartNo () + "&nbsp;</td>" );
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' wrap>" + lineItem.getLineItemDescription () + "&nbsp;</td>" );
                            buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getShippedQtyAsString()  + "&nbsp;</td>" );
                            buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getShippedDate () + "&nbsp;</td>" );
                            buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getUnitPriceAsString () + "&nbsp;</td>" );
                            buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getAmountAsString()  + "&nbsp;</td>" );
                            buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" +  lineItem.getReason() + "&nbsp;</td>" );
                            buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center nowrap>" + lineItem.getAdjustmentQtyAsString()  + "&nbsp;</td>" );
                            buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=right nowrap>" + lineItem.getDiscountPriceAsString()  + "&nbsp;</td>" );
                            buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=right nowrap>" + lineItem.getDiscountAmountAsString()  + "&nbsp;</td>" );
                            buf.append ( "</tr>" );
                }
                if ( lineItemsPresent )
                {
                    buf.append ( "<tr><td colspan='12' align='right' class='NArialL'>Total: &nbsp;</td>" );
                    buf.append ( "<td class='NArialL' align='right' nowrap>" + creditNoteForm.getTotalAdjustmentAmountAsString() + "</td></tr>" );
                }
                buf.append ( "</table>" );
                if( !lineItemsPresent )
                {
                    buf.append ( "<font class='NArialL'><li>All the line items have been cancelled.</font>");
                }
                buf.append ( "</td></tr>" );
                buf.append ( "<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "</table>" );
        buf.append ( "</td></tr> ");
        buf.append ( "</p>" );
        buf.append ( "</table>" );
        if(ConfigManager.getShowTermsLabel() )
        {
            buf.append ( "<table width='98%' bordercolor='#000000' cellspacing='0' cellpadding='2' border=0\n" +
                "align='center'><TR><TD width='98%' class='NArialRS'><p>SpectraLinears Standard Terms and conditions of Sale are enclosed\n" +
                "and are the terms and conditions upon which this Order Acknowledgement is issued. Unless otherwise stated in a written\n" +
                "agreement signed by SpectraLinear. SpectraLinears Standard Terms and Conditions of Sale shall apply to customers\n" +
                "purchase order and shall prevail over any conflicting or additional terms in customers purchase order or other documents\n" +
                "or forms used by customer, which shall be of no effect. </p></TD></TR></table></td></tr></p>");
        }
        buf.append ( "<p STYLE='page-break-after:\n" +
                "always'></p><table width='98%' bordercolor='#000000' border='0' cellspacing='0' cellpadding='0' align='center'><TR><TD\n" +
                "width='100%' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/Terms and Condition of Sale.jpg' width='1000'/></TD></TR></table></body></html>" );
        return buf.toString ();
    }
}
